package cn.tedu.fengyuback.personal.service.impl;

import cn.tedu.fengyuback.base.constent.Constant;
import cn.tedu.fengyuback.personal.mapper.FavoritesMapper;
import cn.tedu.fengyuback.personal.mapper.PersonalMapper;
import cn.tedu.fengyuback.personal.pojo.dto.ArticlesQuery;
import cn.tedu.fengyuback.personal.pojo.dto.FavoritesQuery;
import cn.tedu.fengyuback.personal.pojo.dto.LikesQuery;
import cn.tedu.fengyuback.personal.pojo.vo.ArticlesVO;
import cn.tedu.fengyuback.personal.pojo.vo.FavoritesVO;
import cn.tedu.fengyuback.personal.pojo.vo.LikesVO;
import cn.tedu.fengyuback.personal.service.FavoritesService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class FavoritesServiceImpl implements FavoritesService {
    @Autowired
    FavoritesMapper favoritesMapper;
    @Autowired
    PersonalMapper personalMapper;

    /**
     * 查询收藏的文章
     * @param favoritesQuery
     * @return
     */
    @Override
    public List<ArticlesVO> selectFavorite(FavoritesQuery favoritesQuery) {
        log.debug("开始处理查询收藏文章的业务");
        //查询收藏文章
        List<FavoritesVO> FavoritesVOS = favoritesMapper.selectFavorites(favoritesQuery);
        //设置集合保存查询收藏文章的参数
        ArticlesQuery articlesQuery = new ArticlesQuery();
        //设置集合保存收藏文章的具体内容
        List<ArticlesVO> articlesVOS = new ArrayList<>();
        for (FavoritesVO favoritesVO : FavoritesVOS){
            articlesVOS.add(queryFavorites(articlesQuery,favoritesVO));
        }
//        log.debug("查询到的文章信息为：{}",articlesVOS);
        return articlesVOS;
    }

    /**
     * 查询收藏文章具体内容
     *
     * @param articlesQuery
     * @param favoritesVO
     */
    private ArticlesVO queryFavorites(ArticlesQuery articlesQuery, FavoritesVO favoritesVO) {
        articlesQuery.setId(favoritesVO.getArticleId());
        ArticlesVO articlesVO = personalMapper.selectByIdArticle(articlesQuery).get(0);
        //设置收藏表id、收藏状态
        articlesVO.setFavoritesId(favoritesVO.getId());
        articlesVO.setFavoritesStatus(Constant.ARTICLE_LIKE_FAVORITES);
        queryLike(favoritesVO,articlesVO);
        return articlesVO;
    }

    /**
     * 查询收藏页面被点赞的文章
     * @param articlesVO
     * @param favoritesVO
     * @return
     */
    private void queryLike(FavoritesVO favoritesVO, ArticlesVO articlesVO) {
        LikesQuery likesQuery = new LikesQuery();
        likesQuery.setArticleId(favoritesVO.getArticleId());
        LikesVO likesVO = personalMapper.selectLikes(likesQuery);
        if (likesVO != null){
            articlesVO.setLikesId(favoritesVO.getId());
            articlesVO.setLikesStatus(Constant.ARTICLE_LIKE_FAVORITES);
        }else {
            articlesVO.setLikesStatus(Constant.NOT_ARTICLE_LIKE_FAVORITES);
        }
    }
}
